package com.stars.easyms.rest.manager;

import com.stars.easyms.base.util.ApplicationContextHolder;
import com.stars.easyms.redis.exception.DistributedLockTimeoutException;
import com.stars.easyms.redis.lock.DistributedLock;
import com.stars.easyms.redis.template.EasyMsRedisTemplate;
import com.stars.easyms.rest.constant.RestConstants;
import org.slf4j.Logger;
import org.springframework.lang.Nullable;

import java.util.concurrent.TimeUnit;

/**
 * <p>className: EasyMsRestRedisManager</p>
 * <p>description: EasyMsRest相关redis管理类</p>
 *
 * @author guoguifang
 * @version 1.7.1
 * @date 2020/12/18 10:22 上午
 */
public class EasyMsRestRedisManager {

    private EasyMsRedisTemplate easyMsRedisTemplate;

    @Nullable
    public String getRedisKeyWithPrefix(String... args) {
        if (easyMsRedisTemplate != null) {
            return easyMsRedisTemplate.getRedisKeyWithPrefix(args);
        }
        return null;
    }

    public boolean setIfAbsent(String redisKey, Object value, long timeout, TimeUnit timeUnit) {
        if (easyMsRedisTemplate != null) {
            return easyMsRedisTemplate.setIfAbsent(redisKey, value, timeout, timeUnit);
        }
        return true;
    }

    @Nullable
    public String get(String redisKey) {
        if (easyMsRedisTemplate != null) {
            return easyMsRedisTemplate.get(redisKey);
        }
        return null;
    }

    public boolean getLock(String item, int expireSecond, long timeout, long retryInterval, Logger log) {
        boolean lockFlag = false;
        if (timeout > 0) {
            try {
                DistributedLock.tryBlockLock(RestConstants.REST_LOCK, item, expireSecond, timeout, retryInterval);
                lockFlag = true;
            } catch (DistributedLockTimeoutException e) {
                // 正常流程，无需使用error级别
                log.info(e.getMessage());
            }
        } else {
            lockFlag = DistributedLock.tryLock(RestConstants.REST_LOCK, item, expireSecond);
        }
        return lockFlag;
    }

    public void unlock(String item) {
        DistributedLock.unlock(RestConstants.REST_LOCK, item);
    }

    public EasyMsRestRedisManager() {
        this.easyMsRedisTemplate = ApplicationContextHolder.getBean(EasyMsRedisTemplate.class);
    }
}
